// pages/message/message.js
var config = require('../../config.js');
var sexMap={'男':1,'女':2};
var businessTypeIds = [];
var businessTypeNames = [];
var businessTypeMap = {};
var currentPage = {};
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    workerId: '',
    workerCode: '',
    name: '',
    businessType: '',
    businessTypeShow: [],
    sex: '',
    sexShow: ['女', '男'],
    idCard: '',
    openingBank: '',
    bankAccount: '',
    address: '',
    phone: '',
    criticalPerson: '',
    criticalPhone: '',
    idCardImgShow:[],
    idCardfanImgShow: [],
    idCardFrontImg: '',
    idCardBackImg: '',
    technicalLicenseImg: '',
    technicalLicenseImgShow: [],
    agreementShow:false,
    agreementChecked:'',
    saveBtnDisabled: true,
    technicalLicenseImgMaxCount: 0,
    phoneFlag:false,
    selectIndex:-1
  },
  changSex:function(e){
    currentPage.setData({
      key: e.target.dataset.index
    });
    currentPage.setData({ sex: sexMap[currentPage.data.sexShow[e.target.dataset.index]]});
    console.log(currentPage.data.sex);
  },
  nameInput: function (e) {
    currentPage.setData({
      name: e.detail.value
    })
  },
  openingBankInput: function (e) {
    currentPage.setData({
      openingBank: e.detail.value
    })
  },
  bankAccountInput: function (e) {
    currentPage.setData({
      bankAccount: e.detail.value
    })
  },
  addressInput: function (e) {
    currentPage.setData({
      address: e.detail.value
    })
  },
  phoneInput: function (e) {
    currentPage.setData({
      phone: e.detail.value
    })
  },
  idCardInput: function (e) {
    currentPage.setData({
      idCard: e.detail.value
    })
  },
  criticalPersonInput: function (e) {
    currentPage.setData({
      criticalPerson: e.detail.value
    })
  },
  criticalPhoneInput: function (e) {
    currentPage.setData({
      criticalPhone: e.detail.value
    })
  },
  businessTypeChange(e) {
    var businessTypeId = businessTypeIds[e.detail.value];
    var businessTypeName = businessTypeNames[e.detail.value];
    
    console.log('businessTypeId:' + businessTypeId);
    console.log('businessTypeName:' + businessTypeName);
    
    currentPage.setData({
      businessType: businessTypeId
    });
    currentPage.setData({
      selectIndex: e.detail.value
    });
    currentPage.setTechnicalLicenseImgByBusinessType(businessTypeId);
  },
  ChooseIdCardImg() {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.info("选择身份证正面");
        console.info(res.tempFilePaths);
        wx.uploadFile({
          url: config.fileUploadUrl,
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            "Content-Type":
              "multipart/form-data"
          },
          success: function (res) {
            console.info("身份证照上传返回结果");
            console.info(res);
            let data = JSON.parse(res.data);
            if (data.success == true) {
              if (currentPage.data.idCardImgShow.length != 0) {
                currentPage.setData({
                  idCardImgShow: currentPage.data.idCardImgShow.concat(data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord)
                });
              } else {
                currentPage.setData({
                  idCardImgShow: [data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord]
                });
              }
            } else {
              app.tip(res.data.message, "none");
            }
            wx.hideLoading();
            console.log("idCardImgShow:" + currentPage.data.idCardImgShow);
          },
          fail: function (res) {
            wx.hideLoading();
            console.log('上传失败');
          }
        });
        
      },
      complete: function () {
        setTimeout(function () { wx.hideLoading(); }, 2000);
      }
    });
  },

  ChooseIdCardFanImg() {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.info("选择身份证反面");
        console.info(res.tempFilePaths);
        wx.uploadFile({
          url: config.fileUploadUrl,
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            "Content-Type":
              "multipart/form-data"
          },
          success: function (res) {
            console.info("身份证照上传返回结果");
            console.info(res);
            let data = JSON.parse(res.data);
            if (data.success == true) {
              if (currentPage.data.idCardfanImgShow.length != 0) {
                currentPage.setData({
                  idCardfanImgShow: currentPage.data.idCardfanImgShow.concat(data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord)
                });
              } else {
                currentPage.setData({
                  idCardfanImgShow: [data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord]
                });
              }
            } else {
              app.tip(res.data.message, "none");
            }
            wx.hideLoading();
            console.log("idCardfanImgShow:" + currentPage.data.idCardfanImgShow);
          },
          fail: function (res) {
            wx.hideLoading();
            console.log('上传失败');
          }
        });

      },
      complete: function () {
        setTimeout(function () { wx.hideLoading(); }, 2000);
      }
    });
  },
  setTechnicalLicenseImgByBusinessType(businessTypeId){
    if (businessTypeMap[businessTypeId]["photoFlag"] == 1 && businessTypeMap[businessTypeId]["photoNo"] > 0) {
      currentPage.setData({
        technicalLicenseImgMaxCount: businessTypeMap[businessTypeId]["photoNo"]
      });
      currentPage.setData({
        phoneFlag: true
      });
  
    } else {
      currentPage.setData({
        phoneFlag: false
      });
    }
  },
  ChooseTechnicalLicenseImg(){
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.uploadFile({
          url: config.fileUploadUrl,
          filePath: res.tempFilePaths[0],
          name: 'file',
          header: {
            "Content-Type":
              "multipart/form-data"
          },
          success: function (res) {
            console.info("个人会员执照信息上传返回结果");
            console.info(res);
            let data = JSON.parse(res.data);
            if (data.success == true) {
              if (currentPage.data.technicalLicenseImgShow.length != 0) {
                currentPage.setData({
                  technicalLicenseImgShow: currentPage.data.technicalLicenseImgShow.concat(data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord)
                });
              } else {
                currentPage.setData({
                  technicalLicenseImgShow: [data.object + "/loginController/fileUrl.do?id=" + data.list[0] + '&username=' + config.fileUserName + '&password=' + config.filePassWord]
                });
              }
            } else {
              app.tip(res.data.message, "none");
            }
            wx.hideLoading();
            console.log("technicalLicenseImgShow:"+currentPage.data.technicalLicenseImgShow);
          },
          fail: function (res) {
            wx.hideLoading();
            console.log('上传失败');
          }
        });
      },
      complete: function () {
        setTimeout(function () { wx.hideLoading(); }, 2000);
      }
    });
  },
  DelIdCardImgs(e) {
    wx.showModal({
      title: '身份证正面照片认证',
      content: '确定要删除身份证正面照片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          currentPage.data.idCardImgShow.splice(e.currentTarget.dataset.index, 1);
          currentPage.setData({
            idCardImgShow: currentPage.data.idCardImgShow
          })
        }
      }
    })
  },

  DelIdCardFanImgs(e) {
    wx.showModal({
      title: '身份证反面照片认证',
      content: '确定要删除身份证反面照片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          currentPage.data.idCardfanImgShow.splice(e.currentTarget.dataset.index, 1);
          currentPage.setData({
            idCardfanImgShow: currentPage.data.idCardfanImgShow
          })
        }
      }
    })
  },

  DelTechnicalLicenseImgs(e) {
    wx.showModal({
      title: '证照信息',
      content: '确定要删除证照图片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          currentPage.data.technicalLicenseImgShow.splice(e.currentTarget.dataset.index, 1);
          currentPage.setData({
            technicalLicenseImgShow: currentPage.data.technicalLicenseImgShow
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onLoad.." + options);
    currentPage = this;
    var workerInfo = wx.getStorageSync("workerInfo");
    //workerInfo = {};
    //workerInfo.workerId=60;
    //修改会员页面
    if (workerInfo != null && workerInfo.workerId != null && workerInfo.workerId != ''){
      currentPage.loadWorkerInfo({"workerId": workerInfo.workerId});
      //设置“勾选并同意服务协议《xxxx》”隐藏
      currentPage.setData({ 'agreementShow': false });//隐藏协议勾选
      currentPage.setData({ saveBtnDisabled: false });//保存按钮可用
    } else {
      //设置“勾选并同意服务协议《xxxx》”显示
      currentPage.setData({ 'agreementShow': true });//显示协议勾选
      currentPage.setData({ 'agreementChecked': "" });//默认不勾选协议
      currentPage.setData({ saveBtnDisabled: true });//保存按钮不可用，勾选协议后设置为可用
      //获取并设置业务类型
      currentPage.getAndSetBusinessType(null);
      currentPage.setData({ key: 1 });//性别默认设置为男
      currentPage.setData({ sex: 1 });//性别默认设置为男
      currentPage.setData({ phone: wx.getStorageSync("phoneNumber") });//授权获取的电话号码赋值到页面
    } 
  },
  loadWorkerInfo:function(data){//加载个人会员信息
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    wx.request({
      url: config.getIndividualMemberdUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: data,
      success: function (result) {
        wx.hideLoading();
        console.log(result);
        var data = result.data;
        if (data && data.success == true && data.code && data.code == 100) {
          var obj = data.object;
          currentPage.setData({ workerId: obj.workerId });
          currentPage.setData({ name: obj.name });
          currentPage.setData({ workerCode: obj.workerCode });
          currentPage.setData({ idCard: obj.idCard });
          currentPage.setData({ phone: obj.phone });
          currentPage.setData({ address: obj.address });
          currentPage.setData({ criticalPerson: obj.criticalPerson });
          currentPage.setData({ criticalPhone: obj.criticalPhone });
          currentPage.setData({ openingBank: obj.openingBank });
          currentPage.setData({ bankAccount: obj.bankAccount });
          currentPage.setData({ idCardFrontImg: obj.idCardFrontImg });
          currentPage.setData({ idCardBackImg: obj.idCardBackImg });
          currentPage.setData(
          { idCardImgShow: [
              obj.idCardFrontImg + '&username=' + config.fileUserName + '&password=' + config.filePassWord
            ] 
          });
          currentPage.setData(
            {
              idCardfanImgShow: [
                obj.idCardBackImg + '&username=' + config.fileUserName + '&password=' + config.filePassWord
              ]
            });
          currentPage.setData({ technicalLicenseImg: obj.technicalLicenseImg });
          var technicalLicenseImgArr = obj.technicalLicenseImg.split(",");
          for (var i = technicalLicenseImgArr.length - 1; i >=0 ; --i) {
            var technicalLicenseImg = technicalLicenseImgArr[i];
            if (technicalLicenseImg != null && technicalLicenseImg != '') {
              technicalLicenseImg = technicalLicenseImg + '&username=' + config.fileUserName + '&password=' + config.filePassWord;
              technicalLicenseImgArr[i] = technicalLicenseImg;
            } else {
              technicalLicenseImgArr.splice(i, 1);
            }
          }
          currentPage.setData({ technicalLicenseImgShow: technicalLicenseImgArr });
          currentPage.setData({ businessType: obj.businessType });
          currentPage.setData({ sex: obj.sex });
          var index = 1;
          if (obj.sex == 1) {//男
            index = 1;
          } else if (obj.sex == 2) {//女
            index = 0;
          }
          currentPage.setData({
            key: index
          });
          currentPage.getAndSetBusinessType(obj.businessType);
          wx.setStorageSync("workerInfo", obj);
        } else {
          var errMsg;
          if (data && data.message) {
            errMsg = data.message
          } else {
            errMsg = result.statusCode + ":" + result.errMsg
          }
          app.tip(errMsg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        wx.hideLoading()
        app.tip(errMsg, 'none')
      }
    });
  },
  getAndSetBusinessType:function(businessType){//获取并设置行业类型
    wx.request({
      url: config.queryBusinessTypeList,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        'param': '{"startIndex": 0, "pageSize": 100}'
      },
      success: function (result) {
        console.log(result);
        var data = result.data;
        if (data && data.success == true && data.code && data.code == 100) {
          var rows = data.object.rows;
          var selectIndex = -1;
          for (var i = 0; i < rows.length; ++i) {
            businessTypeIds[i] = rows[i]["businessTypeId"];
            businessTypeNames[i] = rows[i]["businessTypeName"];
            businessTypeMap[rows[i]["businessTypeId"]] = rows[i];
            if (businessType != null && businessType != '' && rows[i]["businessTypeId"] == businessType) {
              selectIndex = i;
              currentPage.setTechnicalLicenseImgByBusinessType(businessType);
            }
          }
          currentPage.setData({ businessTypeShow: businessTypeNames });
          console.log("selectIndex:" + selectIndex);
          if (selectIndex != -1) {
            currentPage.setData({
              selectIndex: selectIndex
            });
          }
        } else {
          var errMsg;
          if (data && data.message) {
            errMsg = data.message
          } else {
            errMsg = result.statusCode + ":" + result.errMsg
          }
          app.tip(errMsg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        wx.hideLoading()
        app.tip(errMsg, 'none')
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  agreement: function () {
    wx.navigateTo({
      url: 'agreement',
    })
  },
  checkboxChange: function (e) {
    if (e.detail.value.length > 0) {
      console.log('选中');
      currentPage.setData({ saveBtnDisabled: false});
    } else {
      console.log('未选中');
      currentPage.setData({ saveBtnDisabled: true});
    }
  },
  save: function(e){
    var validateRes = currentPage.validateSaveInfo();
    if (validateRes != null){
      app.tip(validateRes);
      return;
    }
    var idCardImgShow = currentPage.data.idCardImgShow;
    var idCardfanImgShow = currentPage.data.idCardfanImgShow;
    var technicalLicenseImgShow = currentPage.data.technicalLicenseImgShow;
    var idCardFrontImg = idCardImgShow[0];
    var idCardBackImg = idCardfanImgShow[0];
    if (idCardFrontImg.indexOf("&username=") != -1){
      idCardFrontImg = idCardFrontImg.substring(0, idCardFrontImg.indexOf("&username="));
    }
    if (idCardBackImg.indexOf("&username=") != -1) {
      idCardBackImg = idCardBackImg.substring(0, idCardBackImg.indexOf("&username="));
    }
    currentPage.setData({ idCardFrontImg: idCardFrontImg });
    currentPage.setData({ idCardBackImg: idCardBackImg });
    var technicalLicenseImg = '';
    var businessTypeId = currentPage.data.businessType;

    var photoFlag = businessTypeMap[businessTypeId]["photoFlag"];
    var photoNo = businessTypeMap[businessTypeId]["photoNo"];
    if (photoFlag == 1 && photoNo > 0) {
      for (var i = 0; i < technicalLicenseImgShow.length; ++i) {
        //只保存图片张数限制的图片，多于图片张数限制舍弃
        if (i < photoNo){
          var img = technicalLicenseImgShow[i];
          if (img.indexOf("&username=") != -1) {
            img = img.substring(0, img.indexOf("&username="));
          }
          technicalLicenseImg += img + ',';
        }
      }
    }
    
    currentPage.setData({ technicalLicenseImg: technicalLicenseImg });
    var submitUrl = '';
    //修改个人会员信息提交
    if (currentPage.data.workerId != null && currentPage.data.workerId != ''){
      submitUrl = config.udpIndividualMember;
    } else {//注册个人会员信息提交
      submitUrl = config.registerIndividualMemberUrl;
    }

    let submitData = {
      data: encodeURIComponent('{' +
        '"workerId":"' + currentPage.data.workerId + '",' +
        '"name":"' + currentPage.data.name + '",' +
        '"businessType":"' + currentPage.data.businessType + '",' +
        '"sex":"' + currentPage.data.sex + '",' +
        '"idCard":"' + currentPage.data.idCard + '",' +
        '"openingBank":"' + currentPage.data.openingBank + '",' +
        '"bankAccount":"' + currentPage.data.bankAccount + '",' +
        '"address":"' + currentPage.data.address + '",' +
        '"phone":"' + currentPage.data.phone + '",' +
        '"criticalPerson":"' + currentPage.data.criticalPerson + '",' +
        '"criticalPhone":"' + currentPage.data.criticalPhone + '",' +
        '"idCardFrontImg":"' + currentPage.data.idCardFrontImg + '",' +
        '"idCardBackImg":"' + currentPage.data.idCardBackImg + '",' +
        '"technicalLicenseImg": "' + currentPage.data.technicalLicenseImg + '"}')
    }
    wx.request({
      url: submitUrl,
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: submitData,
      success: function (result) {
        wx.hideLoading();
        console.log(result);
        var data = result.data;
        if (data && data.success == true && data.code && data.code == 100) {
          //修改个人会员信息提交
          if (currentPage.data.workerId != null && currentPage.data.workerId != '') {
            currentPage.loadWorkerInfo({ "workerId": currentPage.data.workerId });
            app.tip("修改成功", "none");
          } else {//注册个人会员信息提交
            submitUrl = config.registerIndividualMemberUrl;
            app.tip("注册成功", "none");
            console.info("注册成功，个人登录");
            var userType = '1';
            var userPhone = wx.getStorageSync("phoneNumber");
            wx.request({
              url: config.loginUrl,
              method: 'POST',
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                "userPhone": userPhone,
                "userType": userType
              },
              success: function (result) {
                console.info(result);
                var data = result.data.object;
                if (data!=null){
                  wx.setStorageSync("companyInfo", null);
                  wx.setStorageSync("uid", 0);
                  wx.setStorageSync("workerInfo", data);
                  wx.navigateTo({
                    url: '../index/index',
                  });
                }
              },
              fail: function ({ errMsg }) {
                wx.hideLoading()
                app.tip(errMsg, 'none')
              }
            });
          }
        } else {
          var errMsg;
          if (data && data.message) {
            errMsg = data.message
          } else {
            errMsg = result.statusCode + ":" + result.errMsg
          }
          app.tip(errMsg, 'none')
        }
      },
      fail: function ({ errMsg }) {
        wx.hideLoading()
        app.tip(errMsg, 'none')
      }
    });
  },
  validateSaveInfo: function(){
    var name = app.trim(currentPage.data.name);
    currentPage.setData({ name: name });
    if (app.isNull(name)){
      return "姓名不能为空";
    }
    
    var phone = app.trim(currentPage.data.phone);
    currentPage.setData({ phone: phone });
    if (app.isNull(phone)) {
      return "联系电话不能为空";
    }

    var address = app.trim(currentPage.data.address);
    currentPage.setData({ address: address });
    if (app.isNull(address)) {
      return "联系地址不能为空";
    }

    var idCard = app.trim(currentPage.data.idCard);
    currentPage.setData({ idCard: idCard });
    if (app.isNull(idCard)) {
      return "身份证号不能为空";
    }

    if (idCard.length!=18){
      return "身份证号必须为18位";
    }

    var criticalPerson = app.trim(currentPage.data.criticalPerson);
    currentPage.setData({ criticalPerson: criticalPerson });
    if (app.isNull(criticalPerson)) {
      return "紧急联系人不能为空";
    }

    var criticalPhone = app.trim(currentPage.data.criticalPhone);
    currentPage.setData({ criticalPhone: criticalPhone });
    if (app.isNull(criticalPhone)) {
      return "联系人电话不能为空";
    }

    if (criticalPhone.length != 11) {
      return "联系人电话必须为11位";
    }

    var idCardImgShow = currentPage.data.idCardImgShow;
    if (idCardImgShow == null || idCardImgShow.length < 1){
      return "请上传身份证正面照片";
    }

    var idCardfanImgShow = currentPage.data.idCardfanImgShow;
    if (idCardfanImgShow == null || idCardfanImgShow.length < 1) {
      return "请上传身份证反面照片";
    }

    return null;
  },
  Agreement: function(){

  }
})